package org.vacoor.xqq.core.mod.authc;

import org.vacoor.xqq.core.mod.authc.exception.AuthenticationException;

/**
 */
public abstract class AbstractAuthenticator implements Authenticator {

    @Override
    public AccessToken login(AuthenticationToken authc) throws AuthenticationException {
        if (authc == null) {
            throw new IllegalArgumentException("authentication token must not be null");
        }
        AccessToken info;
        try {
            info = doLogin(authc);
            if (info == null || !info.isAuthenticated()) {
                throw new AuthenticationException("no authentication info found for authentication token");
            }
        } catch (Throwable t) {
            AuthenticationException ae = null;
            if ( t instanceof AuthenticationException ) {
                ae = (AuthenticationException) t;
            }
            if ( ae == null ) {
                ae = new AuthenticationException("login failed for token submission [" + authc + "]", t);
            }

            throw ae;
        }

        return info;
    }

    protected abstract AccessToken doLogin(AuthenticationToken token) throws AuthenticationException;
}
